#include "QEnumProperty.h"
#include "private/QProperty_p.h"

#include <QComboBox>

using namespace QPE;

QEnumProperty::QEnumProperty(const QString& name)
	: QProperty(name, QVariant::Int)
{
	d_ptr->VariantValue = 0;
	d_ptr->VariantValue.convert(QVariant::Int);
}


//! Get the data how it should be displayed
QVariant QEnumProperty::data (int column, int role) const
{
	if(EnumerationLiterals.empty())
		return QVariant();

	int tmpIndex = d_ptr->VariantValue.toInt();

	if(tmpIndex < 0 || tmpIndex >= EnumerationLiterals.count())
		tmpIndex = 0;

	if(column == DPC_Data && Qt::DisplayRole == role)
		return EnumerationLiterals.at(tmpIndex);
	else if(column == DPC_Data && Qt::EditRole == role)
		return tmpIndex;
	else
		return QProperty::data(column, role);
}


//! Returns an editor widget, or NULL if it doesn't supply one
QWidget* QEnumProperty::createEditor(QWidget * parent, const QStyleOptionViewItem& options, const QAbstractItemDelegate* delegate)
{
	Q_UNUSED(options);
	Q_UNUSED(delegate);
	QComboBox* tmpEditor = new QComboBox(parent);
	tmpEditor->clear();
	tmpEditor->addItems(EnumerationLiterals);
	tmpEditor->setCurrentIndex(d_ptr->VariantValue.toInt());

	return tmpEditor;
}

//! Gets the data from the widget
QVariant QEnumProperty::getEditorData(QWidget* editor) const
{
	QComboBox* tmpEditor = qobject_cast<QComboBox*>(editor);
	if(tmpEditor)
		return tmpEditor->currentIndex();

	return QVariant(0);
}

//! Sets the enumeration literals
void QEnumProperty::setLiterals(const QStringList& literals)
{
	EnumerationLiterals = literals;
}

//! Get the settings. This function has to be implemented in a subclass in order to have an effect
QStringList QEnumProperty::getLiterals() const
{
	return EnumerationLiterals;
}

//! Sets the value of the property
void QEnumProperty::setValue(const QVariant& value)
{
	int tmpIndex = value.toInt();

	if(tmpIndex < 0 || tmpIndex >= EnumerationLiterals.count())
		tmpIndex = 0;

	d_ptr->VariantValue.setValue(tmpIndex);
}

QString QEnumProperty::type() const
{
	return "enum";
}

QProperty* QEnumProperty::clone(bool include_children, QProperty* container) const
{
	return QProperty::clone(include_children, container ? container : new QEnumProperty(getName()));
}

void QEnumProperty::setSetting(const QString& key, const QVariant& value)
{
	if(key == "literals")
		setLiterals(value.toString().split(";;"));
}

QVariant QEnumProperty::getSetting(const QString& key) const
{
	if(key == "literals")
		return getLiterals().join(";;");
	else
		return QProperty::getSetting(key);
}

QStringList QEnumProperty::getSettingKeys() const
{
	return QStringList("literals");
}
